package com.shuai.edit;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shuai.sql.SQL;
import com.shuai.stickynote.EditActivity;
import com.shuai.tool.ClassFactory;
import com.shuai.tool.IDManager;
import com.shuai.stickynote.R;
import com.shuai.stickynote.TextNote;
import com.shuai.tool.SendTool;
import com.shuai.tool.MyTime;

public class TextEditActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView iv_delete, iv_theme;//顶部菜单（清空，主题）
    private EditText et_title, et_content;//标题编辑框，内容编辑框
    private TextView tv_text1, tv_text2, tv_text3, tv_text4;//底部常用字符
    private ImageView iv_yuyin;//语音录入按钮
    private TextView tv_activityTitle;//活动标题标签
    private ImageView btn_back;//返回按钮

    private int etFlag = 0;//编辑框焦点标识，0代表标题，1代表内容
    private SQL sql;//数据库读写工具

    private String title, content;//标题与内容信息

    private String[] str3 = {"1.","2.","3.","4.","5.","6.","7.","8.","9.","10."};
    private String[] str4 = {"①","②","③","④","⑤","⑥","⑦","⑧","⑨","⑩"};
    private int t3Count = 0;
    private int t4Count = 0;

    private String id = "";
    private TextNote sticky = null;
    private TextNote bSticky = null;

    private String TAG = "fuck";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_edit);
        init();
    }
//    初始化
    private void init(){
//        找到控件
        iv_delete = findViewById(R.id.topbar_edit_delete);
        iv_theme = findViewById(R.id.topbar_edit_theme);
        et_title = findViewById(R.id.text_edit_title);
        et_content = findViewById(R.id.text_edit_content);
        tv_text1 = findViewById(R.id.text_edit_text1);
        tv_text2 = findViewById(R.id.text_edit_text2);
        tv_text3 = findViewById(R.id.text_edit_text3);
        tv_text4 = findViewById(R.id.text_edit_text4);
        iv_yuyin = findViewById(R.id.text_edit_yuyin);
        tv_activityTitle = findViewById(R.id.topbar_tv_title);
        btn_back = findViewById(R.id.topbar_btn_back);
//        设置活动标题
        tv_activityTitle.setText("及时便签");
//        设置监听
        tv_text1.setOnClickListener(this);
        tv_text2.setOnClickListener(this);
        tv_text3.setOnClickListener(this);
        tv_text4.setOnClickListener(this);
        iv_yuyin.setOnClickListener(this);
        iv_theme.setOnClickListener(this);
        iv_delete.setOnClickListener(this);
//        监听编辑框的焦点变化
        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) etFlag = 0;
                else etFlag = 1;
                t3Count = 0;
                t4Count = 0;
                tv_text3.setText(str3[t3Count]);
                tv_text4.setText(str4[t4Count]);
            }
        });
        et_title.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                et_title.clearFocus();
                et_content.requestFocus();
                return true;
            }
        });
        et_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) etFlag = 1;
            }
        });
        tv_text3.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                t3Count = 0;
                tv_text3.setText(str3[t3Count]);
                return true;
            }
        });
        tv_text4.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                t4Count = 0;
                tv_text4.setText(str4[t4Count]);
                return true;
            }
        });
        sql = EditActivity.sql;
//        接收传过来的值
        getData();
//        返回按钮监听
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_edit_delete:
                clearContent();
                break;
            case R.id.topbar_edit_theme:
                Toast.makeText(this, "尚未开发哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.text_edit_text1:
                text1();
                break;
            case R.id.text_edit_text2:
                text2();
                break;
            case R.id.text_edit_text3:
                text3();
                break;
            case R.id.text_edit_text4:
                text4();
                break;
            case R.id.text_edit_yuyin:
                yuyin();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            saveData();
        }
        return true;
    }

    private void text1(){
        if (etFlag == 0){
            et_title.getText().insert(et_title.getText().length(),tv_text1.getText().toString());
        }else {
            et_content.getText().insert(et_content.getText().length(),tv_text1.getText().toString());
        }
    }
    private void text2(){
        if (etFlag == 0){
            et_title.getText().insert(et_title.getText().length(),tv_text2.getText().toString());
        }else {
            et_content.getText().insert(et_content.getText().length(),tv_text2.getText().toString());
        }
    }
    private void text3(){
        if (t3Count == 10) t3Count = 9;
        t3Count++;
        Log.d("fuck",t3Count+"");
        if (etFlag == 0){
            et_title.getText().insert(et_title.getText().length(),tv_text3.getText().toString());
        }else {
            et_content.getText().insert(et_content.getText().length(),tv_text3.getText().toString());
        }
        if (t3Count <= 9) tv_text3.setText(str3[t3Count]);
    }
    private void text4(){
        if (t4Count == 10) t4Count = 9;
        t4Count++;
        if (etFlag == 0){
            et_title.getText().insert(et_title.getText().length(),tv_text4.getText().toString());
        }else {
            et_content.getText().insert(et_content.getText().length(),tv_text4.getText().toString());
        }
        if (t4Count <= 9) tv_text4.setText(str4[t4Count]);
    }
    private void clearContent(){
        if (et_content.getText().toString().equals(""))
            Toast.makeText(this, "已经清空了嗷~", Toast.LENGTH_SHORT).show();
        else et_content.setText("");
    }
    private void dealData(){
        if (sticky == null){
            title = et_title.getText().toString();
            content = et_content.getText().toString();
            String id = IDManager.getID();
            String group = id;
            sticky = new TextNote(id, MyTime.toTimeStampForString(MyTime.getCurrentTime()),
                    "text",content,title,group,0,0);
        }else {
            bSticky = new TextNote(sticky.getId(),sticky.getTime(),sticky.getType(),sticky.getContent(),
                    sticky.getTitle(),sticky.getGroup(),sticky.getComplete(),sticky.getDelete());
            sticky.setTime(MyTime.toTimeStampForString(MyTime.getCurrentTime()));
            sticky.setContent(et_content.getText().toString());
            sticky.setTitle(et_title.getText().toString());
        }
    }
    private void yuyin(){
        Toast.makeText(this, "待开发", Toast.LENGTH_SHORT).show();
    }
    private void getData(){
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        sticky = sql.selectTextById(id);
        if (sticky != null){
            et_title.setText(sticky.getTitle());
            et_content.setText(sticky.getContent());
        }
    }
    private void sendToWidget(){
        String id = "";
        if (sticky == null) id = bSticky.getId();
        else id = sticky.getId();
        SendTool.sendToWidget(TextEditActivity.this, ClassFactory.getClass(EditActivity.size),
                EditActivity.widgetId, SendTool.WIDGET_ACTION_TEXT,id,SendTool.TYPE_TEXT);
        EditActivity.widgetId = 0;
        EditActivity.size = "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void saveData(){
        dealData();
        if (bSticky != null){
            if (!bSticky.getTitle().equals(sticky.getTitle()) ||
                    !bSticky.getContent().equals(sticky.getContent())){
                new AlertDialog.Builder(TextEditActivity.this)
                        .setTitle("警告")
                        .setMessage("是否修改并保存？")
                        .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                sql.updateTextById(sticky);
                                if (EditActivity.widgetId != 0){
                                    sendToWidget();
                                }
                                Toast.makeText(TextEditActivity.this, "修改并保存成功！", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .create().show();
            }else finish();
        }else if (!et_title.getText().toString().equals("") ||
                !et_content.getText().toString().equals("")){
            new AlertDialog.Builder(TextEditActivity.this)
                    .setTitle("警告")
                    .setMessage("是否保存？")
                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            sql.insertSticky(sticky);
                            if (EditActivity.widgetId != 0){
                                sendToWidget();
                            }
                            Toast.makeText(TextEditActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create().show();
        }else finish();
    }
}